﻿$.autoPage = function(o){
	var g={
		init:function(){
			o = $.extend({
				tool:['User','Password','Lock','Users','Help','Logout']
				,menu:null
				,uiname_menu:window.DATA.path+'_Menu_UI'
				,uiname_tag:window.DATA.path+'_Tag_UI'
			},o);
			g.loadServerTime();
			g.initPage();
			g.layout();
			g.bindEvent();		
			g.loadMenu();		//获取系统菜单
			g.checkLicense();
			g.loadActionSchema();	//获取Action 的Schema
			g.loadAlarm();		//获取系统告警信息
			window.setInterval(g.loadAlarm,5*60000);
		}

			
		,loadServerTime:function(){
			NBI.getServerTime(function(tim){
				if(g.runservertimeinterval)window.clearInterval(g.runservertimeinterval);
				window.DATA.servertime=tim;
				g.runservertimeinterval=window.setInterval(function(){
					var s=window.DATA.servertime.getSeconds();
					window.DATA.servertime.setSeconds(s+1);
				},1000);
				window.setTimeout(function(){
					g.loadServerTime();
				},1000*60*5);
			});
		}

		,runServerTime:function(){
			
		}

		,initPage:function(){
			var html='<div id="menu"><ul id="mainmenu"></ul></div><div id="top"><div id="header"><div id="logo"></div><div id="tool"><ul id="systemmenu"></ul></div></div><div id="tags" class="data"><span id="scrollleft"></span><div><table cellpadding="0" cellspacing="0"><tr id="pagelist"></tr></table></div><span id="scrollright"></span></div></div><div id="middle"></div><div id="bottom"><div id="info"></div><div id="alarm"><ul class="alarm device"></ul></div></div><div id="waiting"></div><div id="screen" style="display:none;"></div>';
			$('body').html(html);
			var a=NBI.DeviceAlarm;
			for(var i=0,l=a.length;i<l;i++){$('#alarm ul').append('<li><a href="#" domain="l10n" msgid_title="'+a[i]+'" title="'+(a[i])+'" name="'+a[i]+'" class="class'+i+'"></a></li>');}
			for(var i=0;i<o.tool.length;i++){$('#systemmenu').append('<li id="'+o.tool[i]+'"><a href="#" class="icon s16 '+o.tool[i]+'" domain="l10n" msgid_title="'+o.tool[i]+'" title="'+(o.tool[i])+'"></a><label></label></li>');}
			$('#User > label').html(window.top.DATA.username);
			loadLang();
		}


		,layout:function(){
			$('body').layout({ 
				center__paneSelector:"#middle"
				,north__paneSelector:"#top"  
				,north__size:57
				,north__spacing_open:0
				,south__paneSelector:"#bottom" 
				,south__size:22
				,south__spacing_open:0
				//,contentSelector:".data"
				//,center__onresize_end: 
			}); 
		}

		//绑定事件
		,bindEvent:function(){
			var $c=$('#tags > div')
			$(window).bind('load resize',function(){
				$c.css({width:$('#tags').width()-$('#scrollleft').width()-$('#scrollright').width()});
			});

			$('#scrollleft').click(function(){
				var w=$c.width()/2;
				$c.animate({scrollLeft: $c.scrollLeft()-w });
			});
			$('#scrollright').click(function(){
				var w=$c.width()/2;
				$c.animate({scrollLeft: $c.scrollLeft()+w });
			});
			$('#alarm a').click(function(){
				window.top.showMenu({
					path:'/DeviceAlarm/'
					,request:'?search=PerceivedSeverity='+$(this).attr('name')
				});
			});
			window.showMenu=g.showTag;
			//添加按钮事件
			$('#Logout').click(g.logout);
			$('#Lock').click(g.lockScreen);
			$('#Password').click(g.changePassword);	
			if(window.DATA.super_user!=='true')$('#Users').remove();
			else $('#Users').click(g.im);
			$('#screen').click(g.unlock);
			//退出时logout
			window.onbeforeunload=function(e){
			}
			window.onunload=function(e){
				if($('#screen').is(':visible'))NBI.logout();
			}
		}

		,checkLicense:function(){
			if(window.top.DATA.super_user==='true'){
				NBI.getLicense(function(n){
					switch (n){
						case 0:
							alert($.l10n.__('no license'));
						break;
						case -1:
							alert($.l10n.__('license expired'));
						break;
						case 1:
							alert($.l10n.__('license count exceeded'));
						break;
					}
				});
			}
		}


		//加载菜单
		,loadMenu:function(json){
			NBI.getPermission();
			NBI.getMenu(g.getCustomMenu);
		}


		//解析菜单, 两层
		,parseMenu:function(json){
			$('#mainmenu').empty();
			var su=window.top.DATA.super_user;
			var permissions=window.top.DATA.permissions;
			var permission=window.top.DATA.permission;
			var html=[];
			$('menu',o.menu).children().each(function(){
				var name=$(this).attr('name');
				html.push('<li name="'+name+'"><a href="#" domain="l10n" msgid="'+name+'">'+name+'</a>');	
				var $items=$(this).children();
				if($items.length>0){
					html.push('<ul>');
					$items.each(function(){
						if(this.nodeName==='line'){
							//html.push('<li class="line"></li>');
						}else{
							var thisapi=$(this).attr('api')?$(this).attr('api').split(','):[];
							var pm=true;
							if(su!=='true'&&$(this).attr('api')!==''){
								for(var i=0,l=thisapi.length;i<l;i++){
									var api=thisapi[i].split('.');
									var n=api[0],p=api[1],c=permission[0],r=permission[1],u=permission[2],d=permission[3];//顺序为[c,r,u,d]
									var m=permissions[n]; 
									switch(p){
										case 'c':
											if( (m&c) !== m)pm=false;
										break;
										case 'r':
											if( (m&r) !== m)pm=false;
										break;
										case 'u':
											if( (m&u) !== m)pm=false;
										break;
										case 'd':
											if( (m&d) !== m)pm=false;
										break;
										case 's':
											if(window.top.DATA.super_user!=='true')pm=false;
										break;
									}
								}
							}
							if(pm){
								var thispath=$(this).attr('path');
								var thisname=$(this).attr('name');
								var thismultiple=$(this).attr('multiple'); 
								var thisdblclick=$(this).attr('dblclick'); 
								html.push('<li class="item" path="'+thispath+'"><a href="#" path="'+thispath+'" name="'+thisname+'" multiple="'+thismultiple+'"  dblclick="'+thisdblclick+'" domain="l10n" msgid="'+thisname+'">'+thisname+'</a></li>');
							}
						}
					});
					html.push('</ul>');
				}
				html.push('</li>');
			});
			html.push('<li><a href="#" domain="l10n" msgid="Window">Window</a><ul id="windowmenu"><li class="item"><a class="nomenu" href="#" action="customizeMenu" domain="l10n" msgid="customize menu">Customize Menu</a></li><li class="item"><a class="nomenu" href="#" action="closeTags" domain="l10n" msgid="Close All">Close All</a></li><li class="item"><a class="nomenu dashboard" href="#" path="/Dashboard/" name="Dashboard"  domain="l10n" msgid="Dashboard">Dashboard</a></li><li class="line"><a></a></li></ul></li>');
			$('#mainmenu').append(html.join(''));
			$('#mainmenu ul').each(function(){ if(!$('li',this).hasClass('item'))$(this).parent().remove(); });
			if(json){
				var names=[];
				for(var i in json){names.push(i);}
				var $li=$('#mainmenu > li');
				$li.each(function(){
					if($(this).attr('name')&&$.inArray($(this).attr('name'),names)===-1)$(this).hide();
				});

				for(var i in json){
					var j=json[i];
					var $ul=$('#mainmenu');
					var $li=$('#mainmenu > li[name="'+i+'"]');
					if($li.length>0){
						$li[0].index=j.index;
					}else{
						var li=document.createElement('li');li.setAttribute('name',i);li.index=j.index;li.innerHTML='<a href="#">'+i+'</a><ul></ul>';
						$ul.prepend(li);
						var $li=$(li);
					}
					var $sul=$('>ul',$li); 
					for(var k in j.menu){
						var l=j.menu[k];
						if(l.type==='line'){
							var line=document.createElement('li');line.className='line';line.index=l.index;
							$sul.append(line);
						}
						var $sli=$('#mainmenu  li  ul  li[path="'+k+'"]');
						if($sli.length>0){
							$sli.each(function(){
								$sul.append(this);
								this.index=l.index;
								if(!l.visible){
									$(this).hide();
								}else{
									$(this).show();
								}
							});
						}
						var $sli=$('#mainmenu  li  ul  li');
						$sli.sort(compareObject('index'));
						$sli.each(function() {
			        			this.parentNode.insertBefore(this,null);
			    			});	
					}
				}
				var $li=$('#mainmenu > li');
				$li.sort(compareObject('index'));
				$li.each(function() {
			       		this.parentNode.insertBefore(this,null);
				});
			}
			$('#mainmenu').clickMenu();
			$('#mainmenu li ul li a').mousedown(function(){
				if($(this).attr('action')) g[$(this).attr('action')]();
				else g.initTag({menu:this});
			});
			loadLang({el:$('#mainmenu')});
			if(!window.UserData[o.uiname_tag])g.getTags();
		}


		//生成标签
		,initTag:function(o){
			/*
			menu:菜单项
			request:页面参数
			reload:重新载入
			noload:不要载人页面
			*/
			var m=o.menu;
			var r=o.request;
			var rl=o.reload;
			var nl=o.noload;
			if(m.$tag){
				m.$tag.click();
				if(rl){
					m.$tag[0].window.src=$(m).attr('path')+'_GUI/index.html'+(r||'');
				}
				return;
			}
			var name=$(m).attr('name');
			var path=$(m).attr('path');
			var dblclick=$(m).attr('dblclick');
			var multiple=$(m).attr('multiple');			
			var $c=$('#tags > div');
			var s=$('#scrollleft').width();
			$('#pagelist').append('<td><div><a class="title" domain="l10n" msgid="'+name+'">'+name+'</a><a class="close"></a></div></td>');			
			var $tag=$('#pagelist td:last');
			var tag=$tag[0];
			tag.path=$(m).attr('path');
			if(multiple!=='true'){m.$tag=$tag;}
			$tag.click(function(){
				$('#pagelist td.selected').removeClass('selected');
				$tag.addClass('selected');
				var l=tag.offsetLeft;
				var w=tag.offsetWidth;
				if(l+w-s>=$c.scrollLeft()+$c.width())$c[0].scrollLeft=l+w-$c.width();
				if(l<$c.scrollLeft())$c.animate({scrollLeft: l-s-1},0); 
				$('#middle iframe').hide();
				if(!tag.window){
					tag.name=name;
					tag.path=path;
					tag.dblclick=dblclick;
					tag.window=document.createElement('iframe');
					tag.window.src=(/\/$/.test(path)?path+'_GUI/index.html':path)+(r||'');
					$(tag.window).attr('frameborder','0');
					$('#middle').append(tag.window);
					tag.window.contentWindow.mainMenuTag=tag;
				}
				$(tag.window).show();
				g.saveTags();
			})
			if(!nl)$tag.click();

			if(!$(m).hasClass('nomenu')){
				$('#windowmenu').append('<li><a domain="l10n" msgid="'+name+'">'+$.l10n.__(name.toLowerCase())+'</a></li>');
				var a=$('#windowmenu a:last')[0];
				$tag[0].windowmenuitem=a.parentNode;
				$(a).click(function(){$tag.click();});
			}

			var $close=$('a.close',$tag);
			$close.mousedown(function(){
				if($tag.next().length>0){
					$tag.next().click();
				}
				else{
					 if($tag.prev().length>0){$tag.prev().click();}
				}
				$(tag.window).remove();
				$tag.remove();
				$(a).parent().remove();
				m.$tag=null;
			});
			loadLang({el:$tag});

			$('#pagelist').sortable('destory').sortable({
				axis:'x'
				,stop:g.saveTags
			});
		}


		//按菜单路径显示标签
		,showTag:function(o){
			var $m=$('#mainmenu a[path="'+o.path+'"]');
			o.menu=$m[0];
			if($m.length>0)g.initTag(o);
		}


		//自定义菜单
		,customizeMenu:function(){
			new Win({
				url:'customizemenu.html'
				,width:800
				,height:400
				,maxmize:true
				,fromWinObject:{
					menu:o.menu
					,uiname:o.uiname_menu
					,uidata:window.UserData[o.uiname_menu].data
					,fn:g.parseCustomMenu
				}
			});
		}

		//关闭所有标签
		,closeTags:function(s,r,reload){
			$('#tags td,#middle iframe').remove();
			$('#mainmenu li ul li a').each(function(){
				if(this.$tag){
					try{$(this.$tag[0].windowmenuitem).remove();}catch(e){}
					this.$tag=null;
				}
			});
			g.saveTags();
		}

		//加载系统告警信息
		,loadAlarm:function(){
			NBI.getDeviceAlarm(g.parseAlarm);
		}


		//解析系统告警信息
		,parseAlarm:function(data,l){
			for(var v in l){
				$('#alarm a[name="'+l[v]+'"]').text("0");
				data.each(function(){
					if(l[v] === $(this).find('PerceivedSeverity').text()){
						$('#alarm a[name="'+l[v]+'"]').text($(this).find('__count').text());
						return;
					}
				})
			}
		}


		//获取Action Schema作为全局的参数
		,loadActionSchema:function(){ 
			NBI.getSchema({type:'action'});
		}


		//注销
		,logout:function(){
			new window.top.Win({
				url:'logout.html'
				,title:'Logout'//国际化字串
			})
		}

		//更改密码
		,changePassword:function(){
			new window.top.Win({
				url:'changepassword.html'
				,title:'Change Password'//国际化字串
			})
		}


		//注销
		,im:function(){
			new window.top.Win({
				url:'users.html'
				,id:'users_list'
				,title:'Users'//国际化字串
				,type:'tool'
				,modal:false
			})
		}

		//保存标签		
		,getTags:function(){
			NBI.getUserData({
				data:{name:o.uiname_tag}
				,fn:function(data){
					if(window.UserData[o.uiname_tag].api==='edit'){
						g.setTags(window.UserData[o.uiname_tag].data,true);
					}else{
						g.initTag({menu:$('#windowmenu li a.dashboard')[0]});
					}
				}
			});
		}


		,saveTags:function(){
			var json=[];
			$('#pagelist td').each(function(){
				json.push({
					path:this.path
					,selected:$(this).hasClass('selected')
				});
			});
			NBI.setUserData({
				json:json
				,name:o.uiname_tag
			});
		}


		
		,setTags:function(json){
			var s;
			for(var i=0,l=json.length;i<l;i++){
				var j=json[i];
				g.showTag({path:j.path,noload:true})
				if(j.selected)s=j.path;
			}
			g.showTag({path:s})
		}

		//获取保存的菜单
		,getCustomMenu:function(data){			
			o.menu=data;
			NBI.getUserData({
				data:{name:o.uiname_menu}
				,fn:function(data){
					if(window.UserData[o.uiname_menu].api==='edit'){
						g.parseCustomMenu(window.UserData[o.uiname_menu].data);
					}else{
						g.parseCustomMenu();
					}
				}
			});
		}


		,parseCustomMenu:function(json){ 
			window.UserData[o.uiname_menu].data=json;
			window.DATA.customMenu=json; //保存为自定义系统菜单json
			g.parseMenu(json);
		}

		,addMenu:function(m,index){
			var $li=$('#mainmenu td:last');
			name=m;
			$td.after('<td valign="top" name="'+name+'"><div><span class="icon s12 edit"></span><span class="icon s12 add"></span><span class="icon s12 delete"></span></div><a href="#"><label>'+name+'</label></a><ul></ul></td>');
			if(index)$('.editMenu td:last')[0].index=index;
			g.bindEvent();
		}

		,lockScreen:function(){
			NBI.lockScreen(g.showUnlock);
		}

		,showUnlock:function(){
			$('#screen').show();
		}

		,unlock:function(){
			new window.top.Win({
				url:'login.html'
				,title:'Unlock'//国际化字串
				,fromWinObject:{
					unlock:function(){
						$('#screen').remove();
					}
				}
			})			
		}
	}


	g.init();
	return g;
}